package com.whynot.frame.basic.mybatis.config.dynamic;

import com.whynot.frame.basic.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 描述: 获取当前数据源的句柄:
 * 作者: chenyao
 * 日期: 2018-01-30.
 * 项目名称: curtain-whynot-basic-mybatis
 * 版本: 1.0.0
 * JDK: since 1.8
 */
public class DataSourceContextHolder {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);

    /**
     * 默认数据源
     */
    public static final String DEFAULT_DS = "datasource";

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    // 设置数据源名
    public static void setDB(String dbType) {
        logger.info("切换到{"+dbType+"}数据源");
        contextHolder.set(dbType);
    }

    // 获取数据源名
    public static String getDB() {
        return (StringUtils.isEmpty(contextHolder.get()) ? DEFAULT_DS:contextHolder.get());
    }

    // 清除数据源名
    public static void clearDB() {
        contextHolder.remove();
    }
}
